﻿using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;


namespace SEPD.CAD.Template.Palette
{
    public partial class TemplatePaletteSetViewModel : BindableBase
    {

        [CommandMethod("SelectEntity")]
        public IList<Entity> SelectEntity()
        {
            List<Entity> entitys = new List<Entity>();

            //-----------

            //当前选项卡文档
            Document document = Application.DocumentManager.MdiActiveDocument;
            //编辑器
            Editor editor = Application.DocumentManager.MdiActiveDocument.Editor;


            PromptSelectionResult promptSelRes = editor.SelectImplied();//得到选择集状态
            SelectionSet selectionSet;

            //判断是否有已选项  其实反正都要清空选择  此步判断可跳过
            //if (promptSelRes.Status == PromptStatus.OK)
            //{
            //    selectionSet = promptSelRes.Value;
            //    editor.WriteMessage($"selected num :{selectionSet.Count.ToString()}");
            //}
            //else
            //{
            //    editor.WriteMessage($"selected num :0");
            //}

            //创建空数组
            ObjectId[] emptyObjectId = new ObjectId[0];
            editor.SetImpliedSelection(emptyObjectId);  //设置选择集 指向空数组

            //开始请求从图形工程界面选择图元
            promptSelRes = editor.GetSelection();

            //判断是否选中
            if (promptSelRes.Status == PromptStatus.OK)
            {
                selectionSet = promptSelRes.Value;
                editor.WriteMessage($"selected num :{selectionSet.Count.ToString()}");
                List<ObjectId> objectIds = selectionSet.GetObjectIds().ToList();

                Database database = HostApplicationServices.WorkingDatabase;
                using (Transaction transaction = database.TransactionManager.StartTransaction())
                {
                    objectIds.ForEach(oid => entitys.Add((Entity)oid.GetObject(OpenMode.ForRead)));
                    transaction.Commit();
                }
            }
            else
            {
                editor.WriteMessage($"selected num :0");
            }

            return entitys;
        }


        [CommandMethod("EditEntity")]
        public void EditEntity()
        {
            Document document = Application.DocumentManager.MdiActiveDocument;
            Database database = HostApplicationServices.WorkingDatabase;

            Entity entity = SelectEntity()[0];
            if (entity != null && entity is Circle)
            {
                Circle circle = entity as Circle;
                if (circle != null)
                {
                    //DocumentLock docLock = document.LockDocument();//用于非模态文档锁

                    SetFocus(document.Window.Handle);//提前调用
                    using (DocumentLock docLock = document.LockDocument())
                    {
                        using (Transaction transaction = database.TransactionManager.StartTransaction())
                        {
                            circle = (Circle)entity.ObjectId.GetObject(OpenMode.ForWrite);
                            circle.Radius = 10;
                            transaction.Commit();
                        }
                    }

                }
            }
        }

        /// <summary>
        /// 加载 另外的功能文件 并运行
        /// </summary>
        void TempFunction2()
        {
            Document document = Application.DocumentManager.MdiActiveDocument;
            Editor editor = document.Editor;
            Database database = HostApplicationServices.WorkingDatabase;

            string functionPath = string.Empty;
            Action action = () =>
            {
                if (!File.Exists(functionPath))
                {
                    editor.WriteMessage($"FILE NOT EXIST:\n  ");
                    return;
                }
                try
                {
                    document.SendStringToExecute(@"(load """ + functionPath + @""")",
                        false, false, true);
                }
                catch (System.Exception exp) { editor.WriteMessage($"LOAD ERROR:\n{exp.ToString()} "); }

                try
                {
                    document.SendStringToExecute("Exec ", true, false, false);
                }
                catch (System.Exception exp) { editor.WriteMessage($"EXEC ERROR:\n{exp.ToString()} "); }
            };

            using (DocumentLock docLock = document.LockDocument())
            {
                using (Transaction transaction = document.TransactionManager.StartTransaction())
                {
                    action.Invoke();
                }
            }
        }

        /// <summary>
        /// 在工程界面生成文字
        /// </summary>
        [CommandMethod("CadDbText")]
        public void CadDbText()
        {
            //当前选项卡文档
            Document document = Application.DocumentManager.MdiActiveDocument;
            Database database = HostApplicationServices.WorkingDatabase;

            //编辑器
            Editor editor = document.Editor;
            editor.WriteMessage($"\n ====================running CadDbText====================== \n ");//命令行文字

            //创建文字
            DBText text = new DBText();
            text.Rotation = 90;
            text.TextString = "first dbtext vs c#";
            text.Position = new Autodesk.AutoCAD.Geometry.Point3d(0, 0, 0);
            text.Height = 300;
            text.Color = Autodesk.AutoCAD.Colors.Color.FromRgb(1, 122, 1);

            SetFocus(document.Window.Handle);//提前调用
            Action action = () =>
            {
                AddToModelSpace(database, text);
            };
            //action.Invoke();
            //执行代码  
            using (DocumentLock docLock = document.LockDocument())
            {
                //add to modelspace 加入模型空间
                editor.WriteMessage($"\n start \n ");//命令行文字
                action.Invoke();
                editor.WriteMessage($"\n done \n ");//命令行文字
            }

            //对CAD系统命令
            //document.SendStringToExecute("Zoom E", true, false, false);

        }



        public static ObjectId AddToModelSpace(Database db, Entity ent)
        {
            ObjectId entId = ObjectId.Null;//用于返回添加到模型空间中的实体ObjectId
            //定义一个指向当前数据库的事务处理，以添加直线
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                //以读方式打开块表
                BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);
                var spaceId = bt[BlockTableRecord.ModelSpace];

                //以写方式打开模型空间块表记录.
                if (trans.GetObject(spaceId, OpenMode.ForWrite) is BlockTableRecord btr)
                {
                    entId = btr.AppendEntity(ent);//将图形对象的信息添加到块表记录中
                    trans.AddNewlyCreatedDBObject(ent, true);//把对象添加到事务处理中
                }
                trans.Commit();//提交事务处理
            }
            return entId; //返回实体的ObjectId
        }



    }
}
